<template>
	<view>
		<view class="top pdl-38 pdr-38">
			<view class="title fs42">身份认证</view>
			<text class="desc mgt-20 fs22">上传身份证照片即可快速审核放款</text>
		</view>
		<view class="flex-sb upload_box mgt-61">
			<view class="upload_item flex1" v-for="item in uploadList">
				<view class="df upload_wrap mgb-25">
					<image class="upload_front" :src="item.img" mode="aspectFit"></image>
					<view class="flex-jc-ac photo_wrap">
						<!-- 上传前 -->
						<image class="upload_icon" src="/static/src/authentication/upload_btn.png" mode="aspectFit"
							@click="handleUpload(item.side)" v-if="!item.isUpload"></image>
						<!-- 上传后 -->
						<view class="reupload fs24" @click="handleUpload(item.side)" v-else>重新上传</view>
					</view>
				</view>
				<text class="upload_text fs26">{{item.name}}</text>
			</view>
		</view>
		<!-- 上传后 -->
		<view class="information_box mgl-30 mgr-30 mgt-80 pdt-39 pdb-52 pdl-30 pdr-30" v-if="isFormShow">
			<view class="title fs32">信息核对</view>
			<u-form :model="informationForm" ref="formRef" :error-type="errorType" label-width="180"
				:label-style="informationFormStyle">
				<u-form-item label="真实姓名" prop="realName">
					<u-input v-model="informationForm.realName" height="65" placeholder="请输入真实姓名" clearable
						maxlength="20" @blur="handleInput($event,1)" showWordLimit />
				</u-form-item>
				<u-form-item label="证件号码" prop="idcard">
					<u-input v-model="informationForm.idcard" height="65" placeholder="请输入证件号码" clearable maxlength="20"
						showWordLimit @blur="handleInput($event,2)" />
				</u-form-item>
				<u-form-item label="签发机关" prop="issued">
					<u-input v-model="informationForm.issued" height="65" placeholder="请输入签发机关" clearable maxlength="40"
						showWordLimit @blur="handleInput($event,3)" />
				</u-form-item>
				<u-form-item label="有效期" prop="endDate">
					<view :class="informationForm.startDate?'':'default_time'" @click="handleShow(1)">
						{{informationForm.startDate?informationForm.startDate:'请选择开始时间'}}
					</view>
					<view :class="informationForm.startDate && informationForm.endDate?'active_time':'default_time'">-
					</view>
					<view :class="informationForm.endDate?'':'default_time'" @click="handleShow(2)">
						{{informationForm.endDate?informationForm.endDate:'请选择结束时间'}}
					</view>
				</u-form-item>
				<u-picker v-if="isTimeShow" mode="time" :safe-area-inset-bottom="true" v-model="isTimeShow"
					@confirm="handleConfirm"></u-picker>
			</u-form>
		</view>

		<!-- 上传前 -->
		<view class="upload_precautions mgt-100 pdl-38 pdr-38" v-if="!isFormShow">
			<view class="title fs28">上传须知</view>
			<view class="flex-sb mgt-25">
				<view class="flex-sb flex-col" v-for="item in precautionsList" :key="item">
					<image class="notice_img" :src="item.img" mode="aspectFit"></image>
					<view class="cuetext flex-jc-ac mgt-16">
						<image class="notice_icon" :src="item.icon" mode="aspectFit"></image>
						<text class="notice_text fs22 mgl-9">{{item.text}}</text>
					</view>
				</view>
			</view>
		</view>
		<u-button class="submit_btn mgt-138 fs32" shape="circle" :disabled="disabled" :ripple="true"
			throttle-time="2000" @click="handleShowForm" v-if="!isFormShow">提交</u-button>
		<!-- 上传后 -->
		<u-button class="next_btn mgt-62 fs32" shape="circle" :ripple="true" throttle-time="2000" @click="handleNext"
			v-if="isFormShow">下一步</u-button>
		<view class="mgt-30 pdl-41" v-if="isFormShow">
			<view class="flex-ac mark_box">
				<image class="mark_icon" src="/static/src/authentication/notice.png" mode="aspectFit"></image>
				<text class="mark_text mgl-14 fs24">认证通过后资料不可修改，平台会保护您的个人信息</text>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { useInformation } from '@/store/modules/index.ts'

	import { ref, computed, onMounted, nextTick } from 'vue';

	import { uploadCard } from "@/api/upload";

	import type { uploadItem, precautionsItem, informationItem, informationRules } from "../../../static/src/types/step"

	import IDValidator from 'id-validator';

	const idValidator = new IDValidator();

	const user = useInformation()


	const props = defineProps({
		currentNum: {
			type: Number,
			default: 1
		},
		customerForm: {
			type: Object,
			default: (() => {})
		}
	})


	const uploadList = ref<uploadItem[]>([
		{
			side: "face",
			img: '/static/src/authentication/upload_front.png',
			name: '上传头像面',
			isUpload: false
		},
		{
			side: "back",
			img: '/static/src/authentication/upload_reverseside.png',
			name: '上传国徽面',
			isUpload: false
		}
	])

	const precautionsList = ref<precautionsItem[]>([
		{
			icon: "/static/src/authentication/success_icon.png",
			img: "/static/src/authentication/note_1.png",
			text: "正常拍摄"
		},
		{
			icon: "/static/src/authentication/false_icon.png",
			img: "/static/src/authentication/note_2.png",
			text: "边框缺失"
		},
		{
			icon: "/static/src/authentication/false_icon.png",
			img: "/static/src/authentication/note_3.png",
			text: "照片模糊"
		},
		{
			icon: "/static/src/authentication/false_icon.png",
			img: "/static/src/authentication/note_4.png",
			text: "闪光过强"
		}
	])
	const errorType = ref(['message'])
	const isTimeShow = ref<boolean>(false)
	const isFormShow = ref<boolean>(false)
	const informationForm = ref<informationItem>({
		realName: "",
		idcard: "",
		issued: "",
		startDate: "",
		endDate: "",
	})

	const informationFormStyle = {
		color: '#5A5B66',
		fontFamily: ' PingFang SC',
		fontWeight: '500',
		fontSize: '28rpx'
	}
	const formRef = ref<any>(null);
	const rules = ref<informationRules>({
		realName: [
			{ required: true, message: "请输入真实姓名", trigger: ['change', 'blur'] },
			{ pattern: /^[\u4E00-\u9FA5]+$/, message: "只能输入汉字" },
		],
		idcard: [{ required: true, message: "请输入证件号码", trigger: ['change', 'blur'] }],
		issued: [{ required: true, message: "请输入签发机关", trigger: ['change', 'blur'] }],
		endDate: [
			{ required: true, message: "请选择有效期", trigger: ['change', 'blur'] },
		]
	});
	const typeDate = ref<number>(0)
	const startTimeStamp = ref<number>(0)
	const endTimeStamp = ref<number>(0)

	const emit = defineEmits<{
		(e : 'handleCurrent', data : number) : void;
		(e : 'update', data : object) : void;
	}>();

	const disabled = computed(() => {
		return !(user.identity.faceIsUpload && user.identity.backIsUpload);
	});

	// 处理上传身份证图片
	const handleUpload = (side : string) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['camera', 'album'],
			success: async (res) => {
				try {
					const data = await uploadCard(res.tempFilePaths[0], side);
					if (side === 'face') {
						if (data.data.ossUrl) {
							const currentIdentity = user.getIdentity();
							uploadList.value[0].img = data.data.ossUrl
							uploadList.value[0].isUpload = true
							informationForm.value.realName = data.data.name
							informationForm.value.idcard = data.data.idNumber
							user.setIdentity({
								...currentIdentity,
								faceSide: uploadList.value[0].img,
								faceIsUpload: uploadList.value[0].isUpload,
								name: informationForm.value.realName,
								sex: data.data.sex === '男' ? '0' : '1',
								address: data.data.address,
								ethnicity: data.data.ethnicity,
								idNumber: informationForm.value.idcard,
								birthDate: data.data.birthDate
							});
						}
						return
					}
					if (side === 'back') {
						if (data.data.ossUrl) {
							const currentIdentity = user.getIdentity();
							const date = data.data.validPeriod.split('-')
							uploadList.value[1].img = data.data.ossUrl
							uploadList.value[1].isUpload = true
							informationForm.value.issued = data.data.issueAuthority
							informationForm.value.startDate = date[0].trim()
							informationForm.value.endDate = date[1].trim()
							startTimeStamp.value = new Date(informationForm.value.startDate).getTime();
							endTimeStamp.value = new Date(informationForm.value.endDate).getTime();
							user.setIdentity({
								...currentIdentity,
								backSide: uploadList.value[1].img,
								backIsUpload: uploadList.value[1].isUpload,
								issueAuthority: informationForm.value.issued,
								startDate: informationForm.value.startDate,
								endDate: informationForm.value.endDate,
								validPeriod: data.data.validPeriod
							});
						}
						return
					}
				} catch (error) {
					console.error('上传失败', error);
				}
			}
		})
	}
	//图片上传后显示form
	const handleShowForm = () => {
		isFormShow.value = true
		uni.setStorageSync('isFormShow', true);
		const currentIdentity = user.getIdentity()
		informationForm.value = {
			realName: currentIdentity.name || "",
			idcard: currentIdentity.idNumber || "",
			issued: currentIdentity.issueAuthority || "",
			startDate: currentIdentity.startDate || "",
			endDate: currentIdentity.endDate || "",
		}
	}
	// 打开picker
	const handleShow = (type : number) => {
		typeDate.value = type
		isTimeShow.value = !isTimeShow.value
	}
	// 选择有效期
	const handleConfirm = (e : { year : string; month : string; day : string; timestamp : number }) => {
		const currentIdentity = user.getIdentity();
		if (typeDate.value === 1) {
			let date = new Date(`${e.year}-${e.month}-${e.day}`);
			startTimeStamp.value = date.getTime();
			// console.log(startTimeStamp.value, 'startTimeStamp.value')
			if (startTimeStamp.value >= endTimeStamp.value && informationForm.value.endDate !== '') {
				uni.showToast({
					icon: 'none',
					title: "开始时间不能大于结束时间",
				})
				return
			}
			informationForm.value.startDate = `${e.year}.${e.month}.${e.day}`
			user.setIdentity({
				...currentIdentity,
				startDate: informationForm.value.startDate,
			});
		}
		if (typeDate.value === 2) {
			let date = new Date(`${e.year}-${e.month}-${e.day}`);
			endTimeStamp.value = date.getTime();
			if (startTimeStamp.value >= endTimeStamp.value && informationForm.value.startDate !== '') {
				uni.showToast({
					icon: 'none',
					title: "结束时间不能小于开始时间",
				})
				return
			}
			informationForm.value.endDate = `${e.year}.${e.month}.${e.day}`
			user.setIdentity({
				...currentIdentity,
				endDate: informationForm.value.endDate,
			});
		}
	}

	const handleInput = (e : string, num : number) => {
		const currentIdentity = user.getIdentity();
		switch (num) {
			case 1:
				user.setIdentity({ ...currentIdentity, name: e });
				break;
			case 2:
				user.setIdentity({ ...currentIdentity, idNumber: e });
				break;
			case 3:
				user.setIdentity({ ...currentIdentity, issueAuthority: e });
				break;
		}
	}
	// const validateID = () => {
	//   const isValid = idValidator.isValid(informationForm.value.idcard);
	//   if (isValid) {

	//   } else {
	//     console.log('不合法')
	//   }
	// }

	const handleNext = () => {
		const isValid = idValidator.isValid(informationForm.value.idcard);
		if (isValid) {
			formRef.value.validate((valid : boolean) => {
				if (valid) {
					emit('handleCurrent', 2);
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300
					});
				} else {
					uni.showToast({
						icon: "none",
						title: "请检查信息是否完整",
					})
				}
			});
		} else {
			uni.showToast({
				icon: "error",
				title: "证件号码不合法",
			})
		}

	}
	onMounted(() => {
		const currentIdentity = user.getIdentity();
		if (uni.getStorageSync('isFormShow')) {
			isFormShow.value = uni.getStorageSync('isFormShow')
			nextTick(() => {
				if (formRef.value) {
					formRef.value.setRules(rules.value);
				}
			});
		}
		if (currentIdentity) {
			if (currentIdentity.faceSide) {
				uploadList.value[0].img = currentIdentity.faceSide
				uploadList.value[0].isUpload = true
				informationForm.value.realName = currentIdentity.name
				informationForm.value.idcard = currentIdentity.idNumber
			}
			if (currentIdentity.backSide) {
				uploadList.value[1].img = currentIdentity.backSide
				uploadList.value[1].isUpload = true
				informationForm.value.issued = currentIdentity.issueAuthority
				informationForm.value.startDate = currentIdentity.startDate
				informationForm.value.endDate = currentIdentity.endDate
				startTimeStamp.value = new Date(informationForm.value.startDate).getTime();
				endTimeStamp.value = new Date(informationForm.value.endDate).getTime();
			}
		}
	})
</script>

<style lang="scss" scoped>
	@import '@/style/style.scss';

	:deep(uni-button[disabled]) {
		color: #ffffff;
		background: #C8CCE6;
	}

	.top {
		.title {
			color: #333333;
			font-weight: bold;
			font-family: PingFang SC;
		}

		.desc {
			color: #666666;
			font-weight: 500;
			font-family: PingFang SC;
		}
	}

	.upload_box {
		.upload_item {
			text-align: center;

			.upload_wrap {
				position: relative;

				.upload_front {
					width: 100%;
					height: 201rpx;
				}

				.photo_wrap {
					position: absolute;
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;

					.upload_icon {
						width: 100%;
						height: 78rpx;
					}

					.reupload {
						width: 157rpx;
						height: 60rpx;
						line-height: 60rpx;
						color: #FFFFFF;
						background: rgba(60, 81, 242, .8);
						border-radius: 30rpx;
						font-weight: 500;
						font-family: PingFang SC;
					}
				}
			}

			.upload_text {
				color: #5A5B66;
				font-weight: 500;
				font-family: PingFang SC;
			}
		}
	}

	.information_box {
		background: #FFFFFF;
		box-shadow: 0px 2rpx 12rpx 0px rgba(100, 104, 137, 0.2);
		border-radius: 10rpx;

		.title {
			color: #333333;
			font-weight: bold;
			font-family: PingFang SC;
		}

		.default_time {
			color: rgb(192, 196, 204);
		}

		.active_time {
			color: #303133;
		}
	}

	.upload_precautions {
		.title {
			color: #2D2E33;
			font-weight: 500;
			font-family: PingFang SC;
		}

		.notice_img {
			width: 150rpx;
			height: 106rpx;
		}

		.cuetext {
			.notice_icon {
				width: 22rpx;
				height: 22rpx;
			}

			.notice_text {
				color: #878999;
				font-weight: 500;
				font-family: PingFang SC;
			}
		}
	}

	.submit_btn {
		width: 90%;
		color: #FFFFFF;
		background: #3C51F2;
		height: 100rpx;
		font-weight: bold;
		font-family: PingFang SC;
	}

	.next_btn {
		width: 90%;
		color: #FFFFFF;
		background: #3C51F2;
		height: 100rpx;
		font-weight: bold;
		font-family: PingFang SC;
	}

	.mark_box {
		.mark_icon {
			width: 24rpx;
			height: 24rpx;
		}

		.mark_text {
			color: #EE6816;
			font-family: PingFang SC;
			font-weight: 500;
		}
	}
</style>